package com.study.system.gatewayservice.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.study.system.entity.User;
import com.study.system.gatewayservice.config.WhiteListConfig;
import com.study.system.util.JwtUtils;
import com.study.system.util.RsaUtils;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 令牌解析的过滤器
 */
@Component
public class TokenValidateFilter implements GlobalFilter, Ordered {

    private Logger logger = LoggerFactory.getLogger(TokenValidateFilter.class);

    @Resource
    private WhiteListConfig whiteListConfig;

    //过滤
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //判断请求url是否在白名单，是就放行
        for(String url : whiteListConfig.getWhiteList()){
            if(request.getURI().toString().contains(url)){
                logger.info("白名单放行：{}",request.getURI());
                return chain.filter(exchange);
            }
        }
        //获得token
        String token = request.getHeaders().getFirst("Authorization");
        if(token == null){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            DataBuffer data = response.bufferFactory().wrap("token为空".getBytes());
            return response.writeWith(Mono.just(data));
        }
        //解析token
        try {
            User user = JwtUtils.getUserFromToken(token, RsaUtils.publicKey);
            logger.info("解析成功:{}",user);
            return chain.filter(exchange);
        } catch (Exception e) {
            logger.error("解析失败:{},token:{}",e,token);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            DataBuffer data = response.bufferFactory().wrap("token解析失败".getBytes());
            return response.writeWith(Mono.just(data));
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
